<?php
declare (strict_types = 1);

namespace app\admin\controller\wx;
use think\facade\Cache;
use think\Db;
use app\auth\model\Member;
class TemplateMessage extends WxBase
{
    protected function initialize()
    {
        parent::initialize();
        $this->model = new \app\common\model\TemplateMessage;
        $this->validate = new \app\common\validate\TemplateMessage;
    }
    public function get_industry(){
        $industry = Cache::get('industry');
        if($industry){
            return json(unserialize($industry));
        }else{
            $res = $this->app->template_message->getIndustry();
            Cache::set('industry', serialize($res), 3600 * 24);
            return json($res);
        }
    }
    public function set_industry(){
        $industryId1 = $this->request->param('industryId1',null);
        $industryId2 = $this->request->param('industryId2',null);
        $res = $this->app->template_message->setIndustry($industryId1, $industryId2);
        return json($res);
    }
    public function add_template(){
        $shortId = $this->request->param('shortId',null);
        $res = $this->app->template_message->addTemplate($shortId);
        Cache::delete('wx_template_list'); 
        return json($res);
    }
    public function get_template() {
        $template = Cache::get('wx_template_list');
        if($template){
            return json(unserialize($template)); 
        }else{
            $res = $this->app->template_message->getPrivateTemplates();
            Cache::set('wx_template_list', serialize($res), 3600 * 24);
            return json($res);
        }
    }
    public function del_template() {
        $templateId = $this->request->param('templateId',null);
        $res = $this->app->template_message->deletePrivateTemplate($templateId);
        Cache::delete('wx_template_list'); 
        return json($res);
    }

    public function save_msg() {
        $data = $this->request->post();
        $data['author_id'] = $this->request->uid;
        if(!$this->validate->scene('create')->check($data)){
            return json($this->validate->getError(),500);
        }else {
            $this->model->save($data);
            $right_now = $this->request->param('send_right_now', false);
            if($right_now) {
                $this->send_msg($data['type'], $data['touser'], $this->model->id);
                $this->model->status = 'send';
                $this->model->save();
                return json('模版消息创建成功！已发送！');
            } else {
                return json('模版消息创建成功！');
            }
        }
    }
    // 发送消息
    private function send_msg($type, $touser, $msgid) {
        if($msgid){
            $msg = $this->model->where('id', $msgid)->find();
            if(!$msg) {
                return false;
            }
        }
        switch ($type) {
            case 'all':
                $this->send_all($msg);
                break;
            case 'tags':
                $this->send_by_tags($touser, $msg);
                break;
            case 'openid':
                $this->send_by_openid($touser, $msg);
                break;
            default:
                # code...
                break;
        }
        return true;
    }
    // 群发模版消息
    private function send_all($msg){
        Member::where('wx_subscribe','=',1)->where('block','=','no')->chunk(100, function($member) use($msg){
            foreach($member as $one){
                $this->send_by_openid($one['wx_openid'],$msg);
            }
        });
    }
    // 按标签发送
    private function send_by_tags($tag, $msg){
        Member::whereRaw('JSON_CONTAINS( wx_tags, "'.$tag.'")')->where('block','=','no')->where('wx_subscribe','=',1)->chunk(100, function($member) use($msg){
            foreach($member as $one){
                $this->send_by_openid($one['wx_openid'],$msg);
            }
        });
    }
    // 指定openid发送
    private function send_by_openid($openid, $msg) {
        return  $this->app->template_message->send([
            'touser' => $openid,
            'template_id' => $msg['template_id'],
            'url' => $msg['url'],
            'data' => [
                'first'=>$msg['first'],
                'keyword1' => $msg['keyword1'],
                'keyword2' => $msg['keyword2'],
                'keyword3' => $msg['keyword3'],
                'remark'=>$msg['remark']
            ],
        ]);    
    }
}
